import xml2js from 'xml2js'
import tmpl from './tmpl'
import sha1 from 'sha1'
export const parseXML = xml => new Promise((resolve, reject) => {
  xml2js.parseString(xml, {trim: true}, (err, ctn) => {
    if (err) reject(new Error(err))
    else resolve(ctn)
  })
})

export const format = o => {
  if (typeof o !== 'object') {
    if (typeof o === 'string' || typeof o === 'number') return o
    else return
  }
  let _o = Object.assign({}, o)
  let keys = Object.keys(o)
  for (let key of keys) {
    let v = o[key]
    if (!(v instanceof Array) || v.length === 0) continue
    if (v.length === 1) {
      let _v = v[0]
      if (typeof _v === 'object') {
        _o[key] = format(_v)
      } else {
        _o[key] = (_v || '').trim()
      }
    } else {
      _o[key] = []
      for (let vi of v) {
        _o[key].push(format(vi))
      }
    }
  }
  return _o
}
export const toWXtmpl = (content, msg) => {
  let type = 'text'
  if (Array.isArray(content)) {
    type = 'news'
  }
  if (content && content.type) {
    type = content.type
  }
  let info = Object.assign({}, {
    content: content,
    createTime: Date.now(),
    msgType: type,
    toUserName: msg.FromUserName,
    fromUserName: msg.ToUserName
  })
  return tmpl(info)
}
export const params = data => {
  let s = ''
  for (let k in data) {
    let val = data[k] !== undefined ? data[k] : ''
    s += `&${k}=${val}`
  }
  return s ? s.substring(1) : ''
}
export const sortRaw = (ret, _c) => {
  if (!ret && !typeof ret !== 'object') return
  let o = {}
  let sort = Object.keys(ret).sort()
  for (let v of sort) {
    if (!_c) o[v] = ret[v]
    else o[v.toLowerCase()] = ret[v]
  }
  return params(o)
}
export const randStr = size => {
  if (size && typeof size !== 'number') size = 16
  size = size || 16
  let s = ''
  for (let i = 0; i < size; i++) {
    let n = Math.ceil(Math.random() * 100)
    if (n >= 48 && n <= 90) s += String.fromCharCode(n)
    else s += Math.floor(n / 10)
  }
  return s
}
export const sign = (ticket, url) => {
  let timeStamp = parseInt(Date.now() / 1000, 0) + ''
  let noncestr = randStr()
  let ret = {
    jsapi_ticket: ticket,
    timeStamp: timeStamp,
    noncestr: noncestr,
    url: url
  }
  let signature = sha1(sortRaw(ret, true))
  return {
    noncestr: noncestr,
    timeStamp: timeStamp,
    signature: signature
  }
}
